package com.larry.tinyweb.plugin;

import com.larry.tinyweb.core.Global;
import com.larry.tinyweb.core.RequestEntity;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by larry on 16/9/23.
 *
 * 权限认证插件
 */
public class AuthPlugin implements Plugin{
    @Override
    public void plugin(RequestEntity requestEntity) throws Exception {
        if (!inSession(requestEntity)) requestEntity.login();
    }

    public boolean inSession(RequestEntity requestEntity) {
        if (requestEntity.isStatic()) return true;
        HttpServletRequest request = requestEntity.getRequest();
        String requestURL = request.getRequestURL().toString();
        if (requestURL.contains(Global.loginPath) || requestURL.contains(Global.loginAction)) return true;

        Object ID = request.getSession().getAttribute("ID");
        if (ID == null || !request.getSession().getId().equals(ID.toString())) return false;
        return true;
    }
}
